package com.entrogy.service.impl;

import com.entrogy.api.ThdidPersonApi;
import com.entrogy.bean.SchoolThdidUrlEntity;
import com.entrogy.bean.StudentBaseEntity;
import com.entrogy.bean.StudentIcEntity;
import com.entrogy.bean.StudentEntity;
import com.entrogy.dao.IcCardMapper;
import com.entrogy.dao.SchoolMapper;
import com.entrogy.dao.StudentMapper;
import com.entrogy.service.IcCardService;
import com.entrogy.utils.THDio;
import com.entrogy.utils.constants.Constants;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName IcCardServiceImp
 * @Description
 * @Author luoxingjiang
 * @Date 2019-11-02 上午 10:33
 * @Version 1.0
 **/
@Service
public class IcCardServiceImp implements IcCardService {


    private static final Logger logger = LoggerFactory.getLogger(IcCardServiceImp.class);


    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private ThdidPersonApi thdidPersonApi;

    @Override
    public List<StudentIcEntity> bindStuCard(List<StudentIcEntity> stuIcCardList, Integer schoolCode) {
        List<StudentIcEntity> failBindStudentList = new ArrayList<>();
        for (StudentIcEntity stuIcCardEntity : stuIcCardList){
            Integer studentId = stuIcCardEntity.getStudentId();
            String icCardNumber = stuIcCardEntity.getIcCardNumber();
            // 绑定该张IC卡时，需要判断该IC卡是否已经绑定
            List<StudentEntity> studentFormDbByIcCard = studentMapper.listSchoolAllStudent(schoolCode, null, null, null, null, stuIcCardEntity.getIcCardNumber(), null);
            if (studentFormDbByIcCard.size() > 0){
                logger.error("批量绑定IC卡信息的时候，IC卡号为=>" + icCardNumber + "重复绑定！，该生" + stuIcCardEntity.getStudentName() + "绑定失败！");
                failBindStudentList.add(stuIcCardEntity);
                continue;
            }
            if (studentId != null && icCardNumber != null){
                // 更新我们库里的数据
                StudentEntity studentEntity = new StudentEntity();
                studentEntity.setId(stuIcCardEntity.getStudentId());
                studentEntity.setIcNumber(stuIcCardEntity.getIcCardNumber());
                studentMapper.updateStudent(studentEntity);
                // 更新实义德的后台数据
                StudentBaseEntity studentToThdid = new StudentBaseEntity();
                studentToThdid.setIcNumber(stuIcCardEntity.getIcCardNumber()).setStudentId(stuIcCardEntity.getStudentId());
                thdidPersonApi.updateStudentToAll(studentToThdid, schoolCode);
            }
        }
        return failBindStudentList;
    }
}
